<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>WebSocket 图片传输示例</title>
</head>
<body>
<div class="thumb-box">
  <div class="mt-2">
    <!-- 文件选择框 -->
    <!-- accept 属性表示可选择的文件类型 -->
    <!-- image/* 表示只允许选择图片类型的文件 -->
    <input type="file" id="iptFile" style="display: none;" accept="image/*">

    <!-- 选择头像图片的按钮 -->
    <button class="btn btn-primary" id="btnChoose">选择 & 上传图片</button>
  </div>
</div>
<img id="image">
<script>
  var socket = new WebSocket("ws://176.125.55.233:8080/image");

  socket.binaryType = "arraybuffer"; // 设置二进制类型为 ArrayBuffer

  socket.onopen = function(event) {
  };

  socket.onmessage = function(event) {
    var blob = new Blob([event.data], {type: "image/png,image/jpeg,image/gif"});
    var url = URL.createObjectURL(blob);
    document.getElementById("image").src = url;
  };

  // 点击选择上传图片实际上执行的是 input:file
  let btn = document.getElementById('btnChoose');
  let iptFile = document.getElementById('iptFile');
  btn.addEventListener('click', function () {
    // 使用事件自调用
    iptFile.click();
    iptFile.addEventListener('change',function(e){
      if(!e.target.files) return;
      const f = e.target.files[0];
      //可多次触发
      e.target.value='';
      const reader = new FileReader();
      reader.onload = function(event) {
        const binaryMessage = event.target.result; // 获取二进制数据
        socket.send(binaryMessage); // 发送二进制数据
      };
      reader.readAsArrayBuffer(f);
    });
  })

</script>
</body>
</html>
